import random
import pytest
import time

import zmail
from selenium.common import exceptions
from common.basePage import ConfigManager, email_info
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from common.chrome_driver import wd
from common.readyaml import read_yaml
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC, expected_conditions
from common.log_conf import logger
from soupsieve.css_types import Selector
import requests
import csv

from config.conf import cm

response = requests.get('https://api.ipify.org?format=json')
ip_address = response.json()['ip']


def send_sec_no_mail():
    mail = {
        'from': '39560610@qq.com',
        # 'subject': '测试报告',
        'subject': '请速度提交验证码',
        'content_html': '请在30分钟内提交BOSS登录的验证码，jinkens在等待验证码，如果您30分钟内未输入验证码，程序将退出/'
                        '请在下面的页面中提交，需要提交手机号和验证码，请手机号务必正确且与mydata.yaml中一致，/'
                        '否则验证码不能被识别到。/'
                        '提交地址:http://{}/yanzheng/tijiao.html'.format(ip_address)

    }
    server = zmail.server(*email_info().values())
    server.send_mail(cm.ADDRESSER, mail)
    print('验证码邮件发送成功！')

@pytest.mark.skip
def test_login_boss():
    wd.get(url='https://www.zhipin.com/shanghai/')
    logger.info('打开BOSS直聘登录页面')
    wd.maximize_window()
    logger.info('最大化窗口')
    wd.implicitly_wait(5)
    try:
        #  找到首页的登录按钮，点击登录
        login_button = wd.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[1]/div[4]/div/a[4]')
        login_button.click()
        logger.info('点击登录')
        agreement_checkbox = wd.find_element(By.CLASS_NAME, 'agree-policy')
        agreement_checkbox.click()
        logger.info('点击协议')
        #  输入账号
        account_input = wd.find_element(By.XPATH,
                                        '/html/body/div[1]/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/span[2]/input')
        account_input.send_keys(read_yaml()['BOSS']['boss_account'])
        logger.info('输入账号')
        # 点击发送验证码按钮
        send_code_button = wd.find_element(By.CLASS_NAME, 'btn-sms')
        send_code_button.click()
        send_sec_no_mail()  # 发送邮件要验证码

        logger.info('发送验证码按钮已经点击,34行之前代码运行完成')
        # 这里可能会触发验证，用try容错
        try:
            wd.find_element(By.CLASS_NAME, 'yidun_intelli-text').click()
            # wd.find_element(By.CLASS_NAME, 'geetest_radar_tip_content').click()
            logger.info('成功识别到验证码模块')
        except NoSuchElementException as e:
            logger.warn('未找到验证码模块,尝试第二个')
            try:
                wd.find_element(By.CLASS_NAME, 'geetest_radar_tip_content').click()
                logger.info('第二个验证模块找到，已经点击')
                wd.implicitly_wait(5)
            except NoSuchElementException as e:
                logger.warn('2个验证码都没有找到，请手动验证！')

        print('验证后,请继续操作输入验证码，在验证码填入之前，程序会持续睡眠60秒，程序将持续检测验证码输入位数')

        len_no = len(wd.find_element(By.XPATH,
                                     '//*[@id="wrap"]/div/div[2]/div[2]/div[2]/div[1]/div[2]/div/span/input').get_attribute(
            'value'))
        while len_no != 6:
            len_no = len(wd.find_element(By.XPATH,
                                         '//*[@id="wrap"]/div/div[2]/div[2]/div[2]/div[1]/div[2]/div/span/input').get_attribute(
                'value'))
            print('检测到已经输入{}位验证码，输入6位验证码后自动点击，每4秒检测一次'.format(len_no))
            time.sleep(4)
        else:
            print('检测到6位验证码输入，开始点击')
            logger.info('检测到6位验证码输入，开始点击')
        login_button = wd.find_element(By.CLASS_NAME, 'sure-btn')
        login_button.click()
        logger.error('登录按钮已经点击')
        print('登录按钮已经点击，即将开始进行下一个测试')
    except NoSuchElementException as e:
        logger.error('出错，元素未找到，执行退出，错误代码：' + e)
        quit()

@pytest.mark.skip
def test_search_job():
    logger.info('即将开始岗位搜索,先停顿30S')
    time.sleep(30)  # boss随机拼命刷新，等它30秒，折腾完了再进行
    current_url = wd.current_url
    #  点击首页按钮
    try:
        if current_url == 'https://www.zhipin.com/web/geek/job-recommend':
            wd.find_element(By.XPATH, '/html/body/div[1]/div[1]/div/div/div[1]/div[2]/ul/li[1]/a').click()
            logger.info('回调地址是{}，点击首页'.format(current_url))
            time.sleep(30)  # boss随机拼命刷新，等它30秒，折腾完了再进行
        else:
            wd.find_element(By.XPATH, '/html/body/div[1]/div[1]/div/div/div[1]/div[2]/ul/li[1]/a').click()
            logger.info('回调地址是{}，点击首页'.format(current_url))
            time.sleep(30)  # boss随机拼命刷新，等它30秒，折腾完了再进行

    except Exception as e:
        logger.warn('点击首页功能未实现！错误代码:' + str(e))
    try:
        WebDriverWait(wd, 50).until(EC.presence_of_element_located(By.CLASS_NAME, 'ipt-search'))
        logger.warn('出现搜索框之前，不会进行下一步，如果不是在搜索界面，请点击首页，等待跳转，line:99')
        searchbar = wd.find_element(By.XPATH, 'ipt-search')
        searchbar.send_keys(read_yaml()['BOSS']['job'], Keys.ENTER)
        logger.info('已经输入职业并且按了回车')
    except NoSuchElementException as e:
        logger.warn('未找到搜索框，请注意代码稳定性以及反爬')
    #  点击
    try:
        #  显示等待，耐心等待BOSS折腾

        WebDriverWait(wd, 50).until(EC.presence_of_element_located(By.CSS_SELECTOR, '[ka="sel-business-14"]'))
        area_zone = wd.find_element(By.CSS_SELECTOR, '[ka="sel-business-14"]')
        area_zone.click()
        logger.info('点击预设的区域')


    except NoSuchElementException as e:
        logger.error('未找到你所预设的工作地区，即将停止后续操作，请检查设置或者更新反爬机制')
        quit()
    try:
        #  显式等待，直到所选的区域出现
        WebDriverWait(wd, 50).until(EC.presence_of_element_located(By.CLASS_NAME, 'selected-area-name'))
        wd.find_elements(By.CLASS_NAME, 'job-name')
        logger.info('已经切换到{}的岗位页面，即将开始保存数据')
        #
    except NoSuchElementException as e:
        logger.warn('未找到区域设置信息，请检查，后面将继续尝试搜索，程序继续')
if __name__ == '__main__':
    test_login_boss()